/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers;

import app.models.wx.Account;
import app.wxchat.WxChatMessageProcessor;
import com.github.sog.controller.BasicController;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.Restful;
import com.jfinal.module.wxchat.core.WxchatHandler;
import com.jfinal.module.wxchat.message.OutputMessage;
import com.jfinal.module.wxchat.utils.MessageUtil;
import com.jfinal.module.wxchat.utils.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * <p>
 *
 * 微信前端接口总控制器.
 *
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-08 14:10
 * @since JDK 1.6
 */
@Before(Restful.class)
public class WxapiController extends BasicController{
    private final Logger logger = LoggerFactory.getLogger(WxchatHandler.class);

    public void index() {
        try {
            String signature = getPara("signature");	//微信加密签名
            String timestamp = getPara("timestamp"); 	//时间戳
            String nonce = getPara("nonce");	//随机数
            String echostr = getPara("echostr");//认证字符串

            //TOKEN从后台数据库中读取
            //TODO 可以设置缓存
            String token = Account.dao.list().get(0).getStr("token");
            if (logger.isInfoEnabled()) {
                logger.debug("=================");
                logger.debug("signature: {}", signature);
                logger.debug("timestamp: {}", timestamp);
                logger.debug("nonce: {}", nonce);
                logger.debug("echostr: {}", echostr);
                logger.debug("token: {}", token);
                logger.debug("=================");
            }
            if (echostr != null && SecurityUtil.checkSignature(token, timestamp, nonce, signature)) {
                renderText(echostr);
            } else {
                renderNull();
            }
        } catch (Exception e) {
            logger.error("Error process wxapi", e);
            renderNull();
        }
    }

    public void save() {
        try {
            Map<String, String> map = MessageUtil.parseXml(getRequest());
            if (logger.isInfoEnabled()) {
                logger.debug("The message is：{}", map);
            }
            OutputMessage outputMessage = WxChatMessageProcessor.getInstance().process(map);
            if (outputMessage != null) {
                String xml = MessageUtil.outputMessageToXml(outputMessage);

                logger.debug("xml is : {}", xml);

                renderText(xml);
            } else {
                renderNull();
            }
        } catch (Exception e) {
            logger.error("Error process wxapi", e);
            renderNull();
        }
    }
}
